package com.handydata.antifraud.rule.funcs;

import com.handydata.antifraud.enums.RuleNonQuntityValueConvertEnum;
import com.handydata.antifraud.to.RiskInputTO;
import com.handydata.antifraud.to.RiskMiddleTO;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 公司名称包含中文判断
 */
@Component
public class CalcCompanyContainsChinese extends CalculateAdapter {
    private static final Logger logger = LoggerFactory.getLogger(CalcCompanyContainsChinese.class);
    @Override
    public void doCalc(RiskInputTO riskInputTO, RiskMiddleTO riskMiddleTO) {
        logger.info("{}开始计算公司名称是否包含中文，入参:[公司名称={}]", RULE_CALC_TEXT, riskInputTO.getUnitName());
        String companyName = riskInputTO.getUnitName();
        if(StringUtils.isNotEmpty(companyName)) {
            char[] chars = companyName.toCharArray();
            for(char chr : chars) {
                if(isChinese(chr)) {
                    riskMiddleTO.setCalAHdyR0146Result(RuleNonQuntityValueConvertEnum.MATCH_OK.getCode());
                    return;
                }
            }
        }

        riskMiddleTO.setCalAHdyR0146Result(RuleNonQuntityValueConvertEnum.MATCH_FAIL.getCode());
        logger.info("{}结束计算公司名称是否包含中文, 结果:[CAL_A_HDY_R014计算结果={}]", RULE_CALC_TEXT, riskMiddleTO.getCalAHdyR0146Result());
    }

    // 根据Unicode编码完美的判断中文汉字和符号
    private static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
            return true;
        }
        return false;
    }

    // 完整的判断中文汉字和符号
    public static boolean isChinese(String strName) {
        char[] ch = strName.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            char c = ch[i];
            if (isChinese(c)) {
                return true;
            }
        }
        return false;
    }
}
